<?php
use \PFT\Db;

define('DAY_TIME', 3600 * 24);
//只允许管理员通过ajax方式访问
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
	exit('access error');
}
include('/var/www/html/new/d/common/func.inc.php');
include('/var/www/html/new/d/module/common/Db.class.php');
$db_conf = include('/var/www/html/new/d/module/common/db.conf.php');
Db::Conf($db_conf['remote_1']);
Db::connect();

switch ($_REQUEST['past']) {
    //最近七天
	case 'seven':
		$step = 7;$time_format = 'Y-m-d';
		$begin_time_cur = strtotime(date('Y-m-d'));
		$begin_time_tongbi = strtotime(date('Y-m-d', strtotime('-1 year')));
		// $begin_time_huanbi = strtotime(date('Y-m-d', strtotime('-1 day')));
		break;
    //最近三十天
	case 'thirty':
		$step = 30;$time_format = 'Y-m-d';
		$begin_time_cur = strtotime(date('Y-m-d'));
		$begin_time_tongbi = strtotime(date('Y-m-d', strtotime('-1 year')));
		// $begin_time_huanbi = strtotime(date('Y-m-d', strtotime('-1 day')));
		break;
    //最近一年
	case 'month':
		$step = 11;$time_format = 'Y-m';
		$begin_time_cur = strtotime(date('Y-m-01', time()));
		// $begin_time_tongbi = strtotime(date(date('Y') - 1 . '-11-01'));
		$begin_time_tongbi = strtotime(date('Y-m-01', strtotime('-1 year')));
		// $begin_time_tongbi = strtotime(date('Y-m-d', strtotime('-1 year')));
		// $begin_time_huanbi = strtotime(date(date('Y') . '-11-01'));
		break;
    //上一个季度
	case 'quarter':
        $step = 91;$time_format = 'Y-m-d';
        $threeMonthAgo = mktime(0, 0, 0, date('n', time()) - 3, 1, date('Y', time()));
        $year = date('Y', $threeMonthAgo);
        $month = date('n', $threeMonthAgo);
        $startMonth = intval(($month - 1)/3)*3 + 1; // 上季度开始月份
        $endMonth = $startMonth + 2; // 上季度结束月份
        $time_huanbi= $endMonth-3;
//        var_dump(date('Y-m-d', strtotime($year . "-{$endMonth}-1")));
		$begin_time_cur = strtotime(date('Y-m-d', strtotime($year . "-{$endMonth}-1 + 1 month - 1day")));
		$begin_time_tongbi = strtotime(date('Y-m-d', strtotime(intval($year-1) . "-{$endMonth}-1 + 1 month - 1day")));
		// $begin_time_huanbi = strtotime(date('Y-m-d', strtotime($year . "-{$time_huanbi}-1 + 1 month - 1day")));
		break;
	default:
		exit();
}
$time_arr = array(
	'cur' => $begin_time_cur,
	// 'huanbi' => $begin_time_huanbi,
	'tongbi' => $begin_time_tongbi
);

$data = array();
foreach ($time_arr as $key => $begin_time) {
	for ($i = $step; $i >= 0; $i--) {
		$time_range = get_time_range($begin_time, $i, $_REQUEST['past'], $key);
		$tmp_begin_time = $time_range[0];
		$tmp_end_time = $time_range[1];
		if ($tmp_begin_time > time() || date('Y-m-d', time()) == date('Y-m-d', $tmp_begin_time)) {
			continue;
		}
		// $identify = md5($tmp_begin_time.'-'.$tmp_end_time);
		$field = $_REQUEST['type'] == 'order' ? 'torder' :
			($_REQUEST['type'] == 'ticket' ? 'tnum' : 'money');
		$result = Db::fetch("select sum({$field}) as sum 
				from pft_order_statistics 
				where ddate >= '".date('Y-m-d', $tmp_begin_time)."' and ddate < '".date('Y-m-d', $tmp_end_time)."' 
				limit 1"
		);

		if ($result) {
			$data[$key][] = $result['sum'];
			if ($key == 'cur') {
					$data['date'][] = date($time_format, $tmp_begin_time);
			}
		}
	} 
}
echo json_encode($data);

/**
 * 根据选择时间类型的不同(七天，月，季度，年)计算出对应的同比环比的时间段
 */
function get_time_range($begin_time, $step, $past, $key) {
	switch ($past) {
		case 'seven':
			$tmp_begin_time = $begin_time - $step * DAY_TIME;
			$tmp_end_time = $tmp_begin_time + DAY_TIME;
			break;
		case 'thirty':
			$tmp_begin_time = $begin_time - $step * DAY_TIME;
			$tmp_end_time = $tmp_begin_time + DAY_TIME;
			break;
		case 'month':
			$year = date('Y', $begin_time);
			$month = date('m', $begin_time);
			$reduce = $month - $step - 1;
			if ($reduce < 0) {
				$year = $year - 1;
				$reduce = 12 + $reduce;
			}
			$tmp_begin_time =  strtotime($year .'-'. $reduce);
			if ($reduce + 1 > 12) {
				$year++;
				$reduce = '01';
			} else {
				$reduce++;
			}
			$tmp_end_time = strtotime($year .'-'. $reduce);
			break;
		case 'quarter':
		    $tmp_begin_time =   $begin_time - $step * DAY_TIME;
			$tmp_end_time =  $tmp_begin_time + DAY_TIME;
			break;
		default:
		
			exit();
	}
	return array($tmp_begin_time, $tmp_end_time);
}

/**
 * 获取静态缓存的数据
 * @param  [type] $identify [description]
 * @return [type]           [description]
 */
function get_static_data($identify, $begin_time) {
	$file = './data/order_static.txt';
	$content = json_decode(file_get_contents($file), true);
	if (date('Y-m',time()) == date('Y-m', $begin_time)) {
		if (time() - 3600 > $content[$identify][1]) {
			return false;
		}
	}
	if (isset($content[$identify])) {
		return $content[$identify][0];
	}
	return false;
}

/**
 * 将数据进行缓存（接口查询太慢）
 * @param  [type] $identify [description]
 * @param  [type] $data     [description]
 * @return [type]           [description]
 */
function save_static_data($identify, $data, $begin_time) {
	$file = './data/order_static.txt';
	$content = json_decode(file_get_contents($file), true);
	$write = false;
	if (!isset($content[$identify])) {
		$write = true;
	}
	if (date('Y-m',time()) == date('Y-m', $begin_time)) {
		if (time() - 3600 > $content[$identify][1]) {
			$write = true;
		}
	}
	if ($write) {
		$content[$identify] = array($data, time());
		file_put_contents($file, json_encode($content));
	}
}